package org.edu.eece262.taskshare;

import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RatingBar;
import android.widget.SeekBar;
import android.widget.TimePicker;
import android.widget.Toast;

public class TaskEditor extends Activity {

	private static final int NEW_CHILD = Menu.FIRST;
	private static final int DELETE_ANY = Menu.FIRST + 1;
	private static final int DELETE_THIS = Menu.FIRST + 2;
	private static final int DELETE_CHILDREN = Menu.FIRST + 3;
	private static final int DELETE_THIS_CHILDREN = Menu.FIRST + 4;
	private static final int DATE_DIALOG = 0;
	private static final int TIME_DIALOG = 1;
	private static final String PREFS_NAME = "TASKSHARELOGIN";

	Button bSaveTask;
	Button bCancel;
	Button bTaskDueDate;
	Button bTaskDueTime;
	EditText etTaskName;
	EditText etTaskNotes;
	EditText etTaskLocation;
	SeekBar sbPercent;
	RatingBar rbPriority;

	long global_id;
	int local_id;
	String task_name;
	String task_notes;
	String task_location;
	Calendar date_time;
	int parent_local;
	long parent_global;
	int priority;
	int percent;
	int newDate;
	int newTime;
	int done;

	Intent results;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		results = new Intent();

		setContentView(R.layout.taskeditor);

		bSaveTask = (Button) findViewById(R.id.bSaveTask);
		bCancel = (Button) findViewById(R.id.bCancel);
		bTaskDueDate = (Button) findViewById(R.id.bTaskDueDate);
		bTaskDueTime = (Button) findViewById(R.id.bTaskDueTime);
		etTaskName = (EditText) findViewById(R.id.etTaskName);
		etTaskNotes = (EditText) findViewById(R.id.etTaskNotes);
		etTaskLocation = (EditText) findViewById(R.id.etTaskLocation);
		sbPercent = (SeekBar) findViewById(R.id.sbPercent);
		rbPriority = (RatingBar) findViewById(R.id.rbPriority);

		local_id = getIntent().getIntExtra(TaskDBAdapter.DB_KEY_ID, 0);
		global_id = getIntent().getLongExtra(TaskDBAdapter.KEY_GLOBAL_ID, 0);
		task_name = getIntent().getStringExtra(TaskDBAdapter.KEY_NAME);
		task_notes = getIntent().getStringExtra(TaskDBAdapter.KEY_NOTES);
		task_location = getIntent().getStringExtra(TaskDBAdapter.KEY_LOCATION);
		parent_local = getIntent().getIntExtra(TaskDBAdapter.KEY_PARENT_LOCAL, 0);
		parent_global = getIntent().getLongExtra(TaskDBAdapter.KEY_PARENT_GLOBAL, 0);

		int date = getIntent().getIntExtra(TaskDBAdapter.KEY_DUE_DATE, 0);
		int time = getIntent().getIntExtra(TaskDBAdapter.KEY_DUE_TIME, 0);

		int month;
		int day;
		int year;

		date_time = Calendar.getInstance();

		if (date != 0) {
			year = date / 10000;
			month = (date / 100) % 100;
			day = date % 100;
			date_time.set(year, month, day);
		}

		bTaskDueDate.setText(date_time.toString());

		int hour = time / 100;
		int minute = time % 100;

		date_time.set(Calendar.MINUTE, minute);
		date_time.set(Calendar.HOUR, hour);

		priority = getIntent().getIntExtra(TaskDBAdapter.KEY_PRIORITY, 3);
		percent = getIntent()
				.getIntExtra(TaskDBAdapter.KEY_PERCENT_COMPLETE, 0);

		loadValues();

		bSaveTask.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (updateTask()) {
					makeToast("Task updated successfully.");
					setResult(RESULT_OK, results);
					finish();
				} else {
					makeToast("Task update failed.");
				}
			}
		});

		bCancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				setResult(RESULT_CANCELED);
				finish();
			}
		});

		bTaskDueDate.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showDialog(DATE_DIALOG);
			}

		});

		bTaskDueTime.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showDialog(TIME_DIALOG);
			}

		});

	}

	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG:
			return new DatePickerDialog(this, mDateSetListener, date_time
					.get(Calendar.YEAR), date_time.get(Calendar.MONTH),
					date_time.get(Calendar.DAY_OF_MONTH));
		case TIME_DIALOG:
			return new TimePickerDialog(this, mTimeSetListener, date_time
					.get(Calendar.HOUR), date_time.get(Calendar.MINUTE), false);
		}
		return null;
	}

	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
		// onDateSet method
		public void onDateSet(DatePicker view, int year, int month, int day) {
			date_time.set(Calendar.YEAR, year);
			date_time.set(Calendar.MONTH, month);
			date_time.set(Calendar.DAY_OF_WEEK, day);

			bTaskDueDate.setText(loadDate(year, month, day));
		}
	};

	private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
		// onTimeSet method
		@Override
		public void onTimeSet(TimePicker view, int hour, int minute) {
			date_time.set(Calendar.HOUR, hour);
			date_time.set(Calendar.MINUTE, minute);

			bTaskDueTime.setText(loadTime(hour, minute));
		}
	};

	public void loadValues() {
		etTaskName.setText(task_name);
		etTaskNotes.setText(task_notes);
		etTaskLocation.setText(task_location);
		bTaskDueTime.setText(loadTime(date_time.get(Calendar.HOUR), date_time
				.get(Calendar.MINUTE)));
		bTaskDueDate.setText(loadDate(date_time.get(Calendar.YEAR), date_time
				.get(Calendar.MONTH), date_time.get(Calendar.DAY_OF_MONTH)));
		rbPriority.setProgress(priority);
		sbPercent.setProgress(percent);
	}

	public String loadTime(int hour, int minute) {
		String toReturn = "";
		if (minute < 10) {
			toReturn += ":0" + minute;
		} else {
			toReturn += ":" + minute;
		}

		if (hour == 0) {
			toReturn = "12" + toReturn + " AM";
		} else if (hour > 12) {
			toReturn = ((hour % 12) + toReturn + " PM");
		} else if (hour == 12) {
			toReturn = "12" + toReturn + " PM";
		} else {
			toReturn = (hour + toReturn + " AM");
		}

		return toReturn;
	}

	public String loadDate(int year, int month, int day) {
		switch (month) {
		case 0:
			return "Jan " + String.valueOf(day) + ", " + String.valueOf(year);
		case 1:
			return "Feb " + String.valueOf(day) + ", " + String.valueOf(year);
		case 2:
			return "Mar " + String.valueOf(day) + ", " + String.valueOf(year);
		case 3:
			return "Apr " + String.valueOf(day) + ", " + String.valueOf(year);
		case 4:
			return "May " + String.valueOf(day) + ", " + String.valueOf(year);
		case 5:
			return "Jun " + String.valueOf(day) + ", " + String.valueOf(year);
		case 6:
			return "Jul " + String.valueOf(day) + ", " + String.valueOf(year);
		case 7:
			return "Aug " + String.valueOf(day) + ", " + String.valueOf(year);
		case 8:
			return "Sep " + String.valueOf(day) + ", " + String.valueOf(year);
		case 9:
			return "Oct " + String.valueOf(day) + ", " + String.valueOf(year);
		case 10:
			return "Nov " + String.valueOf(day) + ", " + String.valueOf(year);
		case 11:
			return "Dec " + String.valueOf(day) + ", " + String.valueOf(year);
		default:
			return "Select Date";
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		boolean result = super.onCreateOptionsMenu(menu);
		menu.add(0, NEW_CHILD, 1, R.string.new_child);
		SubMenu delete_any = menu.addSubMenu(0, DELETE_ANY, 2,
				R.string.delete_any);
		delete_any.add(0, DELETE_THIS, 2, R.string.delete_this);
		delete_any.add(0, DELETE_CHILDREN, 2, R.string.delete_children);
		delete_any.add(0, DELETE_THIS_CHILDREN, 2,
				R.string.delete_this_children);

		return result;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case NEW_CHILD:
			if (updateTask()) {
				if (createSubtask()) {
					results.putExtra("NULL", true);
					setResult(RESULT_OK, results);
					makeToast("Subtask created successfully.");
					finish();
				} else {
					makeToast("Subtask creation failed.");
				}
			} else {
				makeToast("Failed to save parent task.");
			}

			break;

		case DELETE_THIS:
			reassign_children(global_id, local_id, parent_global, parent_local);
			TaskDBAdapter.getTSDBAdapter(getApplicationContext()).removeEntry(
					local_id, getApplicationContext());
			results.putExtra("NULL", true);
			setResult(RESULT_OK, results);
			finish();
			break;
		case DELETE_CHILDREN:
			delete_task(global_id, local_id);
			results.putExtra("NULL", true);
			setResult(RESULT_OK, results);
			finish();
			break;
		case DELETE_THIS_CHILDREN:
			delete_task(global_id, local_id);
			TaskDBAdapter.getTSDBAdapter(getApplicationContext()).removeEntry(
					local_id, getApplicationContext());
			results.putExtra("NULL", true);
			setResult(RESULT_OK, results);
			finish();
			break;
		default:
		}

		return super.onOptionsItemSelected(item);
	}

	private void reassign_children(long globalId, int oldParentLocal,
			long parentGlobal, int newParentLocal) {
		Cursor children = TaskDBAdapter.getTSDBAdapter(getApplicationContext())
				.getChildrenOf(oldParentLocal);
		int count = children.getCount();
		if (count > 0) {
			children.moveToFirst();
			while (!children.isAfterLast()) {
				TaskDBAdapter
						.getTSDBAdapter(getApplicationContext())
						.changeParent(
								children
										.getInt(children
												.getColumnIndex(TaskDBAdapter.DB_KEY_ID)),
								newParentLocal, parentGlobal);
				children.moveToNext();
			}
		}

	}

	private void delete_task(long globalId, int localId) {
		Cursor children = TaskDBAdapter.getTSDBAdapter(getApplicationContext())
				.getChildrenOf(localId);
		int count = children.getCount();
		if (count > 0) {
			children.moveToFirst();
			while (!children.isAfterLast()) {
				delete_task(children.getInt(TaskDBAdapter.GLOBAL_ID_COLUMN),
						children.getInt(children
								.getColumnIndex(TaskDBAdapter.DB_KEY_ID)));

				TaskDBAdapter
						.getTSDBAdapter(getApplicationContext())
						.removeEntry(
								children
										.getInt(children
												.getColumnIndex(TaskDBAdapter.DB_KEY_ID)), getApplicationContext());
				children.moveToNext();
			}
		}
	}

	void makeToast(String alert) {
		Toast.makeText(getApplicationContext(), alert, Toast.LENGTH_SHORT)
				.show();
	}

	private boolean updateTask() {
		if (etTaskName.getText().toString().equals("")) {
			etTaskName.setText(getIntent().getStringExtra(
					TaskDBAdapter.KEY_NAME));
		}

		newDate = (date_time.get(Calendar.YEAR) * 10000)
				+ (date_time.get(Calendar.MONTH) * 100)
				+ (date_time.get(Calendar.DAY_OF_MONTH));

		newTime = date_time.get(Calendar.MINUTE);
		newTime += date_time.get(Calendar.HOUR) * 100;

		priority = rbPriority.getProgress();
		task_name = etTaskName.getText().toString();
		task_notes = etTaskNotes.getText().toString();
		task_location = etTaskLocation.getText().toString();
		percent = sbPercent.getProgress();
		done = 0;
		if (percent == 100) {
			done = 1;
		}

		if (parent_global == global_id) {
			parent_global = 0;
		}

		if (TaskDBAdapter.getTSDBAdapter(getApplicationContext()).updateEntry(
				local_id, global_id, task_name, task_notes, task_location,
				parent_local, parent_global, newDate, newTime, percent,
				priority) > 0) {
			return true;
		}
		return false;
	}
	
	private boolean createSubtask()
	{
		if (etTaskName.getText().toString().equals("")) {
			etTaskName.setText(getIntent().getStringExtra(
					TaskDBAdapter.KEY_NAME));
		}

		newDate = (date_time.get(Calendar.YEAR) * 10000)
				+ (date_time.get(Calendar.MONTH) * 100)
				+ (date_time.get(Calendar.DAY_OF_MONTH));

		newTime = date_time.get(Calendar.MINUTE);
		newTime += date_time.get(Calendar.HOUR) * 100;

		priority = rbPriority.getProgress();
		done = 0;

		task_name = "New Subtask";
		task_notes = "This is a temporary description.";
		task_location = "Not set";
		parent_local = local_id;
		parent_global = global_id;
		percent = 0;

		SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
		
		if(TaskDBAdapter.getTSDBAdapter(
				getApplicationContext()).insertEntry(task_name, settings.getString("user", ""),
				task_notes, task_location, parent_local, parent_global,
				newDate, newTime, percent, priority, getApplicationContext()) > 0) {
			return true;
		} else {
			return false;
		}
	}
}
